<template>
  <div class="component">
    <h2>模板编辑器</h2>
    
    <div class="form-group">
      <label>模板名称</label>
      <input 
        v-model="templateData.name" 
        placeholder="输入模板名称"
        class="full-width"
      >
    </div>
    
    <div class="form-group">
      <label>模板描述</label>
      <textarea 
        v-model="templateData.description" 
        placeholder="输入模板描述"
        rows="2"
        class="full-width"
      ></textarea>
    </div>
    
    <div class="form-group">
      <div class="flex justify-between items-center">
        <label>字段配置</label>
        <button 
          @click="addField" 
          class="btn-primary"
        >
          添加字段
        </button>
      </div>
      
      <div 
        v-for="(field, index) in templateData.fields" 
        :key="index" 
        class="field-item"
        :class="{ 'dragging': draggedIndex === index }"
        draggable="true"
        @dragstart="handleDragStart(index, $event)"
        @dragover="handleDragOver($event)"
        @drop="handleDrop(index, $event)"
        @dragend="handleDragEnd"
      >
        <div class="field-header flex gap-2 items-center mb-2">
          <div class="drag-handle" title="拖拽排序" @mousedown.stop>
            <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
              <path d="M6 4H10M6 8H10M6 12H10" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/>
              <path d="M4 4H4.01M4 8H4.01M4 12H4.01" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/>
            </svg>
          </div>
          <input 
            v-model="field.name" 
            placeholder="字段名称"
            class="flex-1 field-input"
            @mousedown.stop
            @dragstart.prevent
          >
          <select v-model="field.type" class="field-select" @change="handleTypeChange(index)" @mousedown.stop @dragstart.prevent>
            <option value="string">字符串</option>
            <option value="number">数字</option>
            <option value="boolean">布尔值</option>
            <option value="object">对象</option>
            <option value="array">数组</option>
            <option value="template">模板嵌套</option>
          </select>
          <!-- 模板选择下拉框，仅当类型为 template 时显示 -->
          <select 
            v-if="field.type === 'template'" 
            v-model="field.templateId" 
            class="w-40"
            @mousedown.stop
            @dragstart.prevent
          >
            <option value="">选择模板</option>
            <option 
              v-for="tpl in props.availableTemplates" 
              :key="tpl.id" 
              :value="tpl.id"
            >
              {{ tpl.name }}
            </option>
          </select>
          <label class="flex items-center" @mousedown.stop>
            <input type="checkbox" v-model="field.required" @dragstart.prevent> 必填
          </label>
          <button 
            @click="removeField(index)" 
            class="btn-danger btn-small delete-button"
            @mousedown.stop
            @dragstart.prevent
            title="删除字段"
          >
            删除
          </button>
        </div>
        
        <div class="flex gap-2">
          <div class="flex-1">
            <label>约束条件</label>
            <input v-model="field.constraint" placeholder="如: 长度>5" @mousedown.stop @dragstart.prevent>
          </div>
          <div class="flex-1">
            <label>格式</label>
            <input v-model="field.format" placeholder="如: email, date" @mousedown.stop @dragstart.prevent>
          </div>
        </div>
      </div>
    </div>
    
    <div class="button-group flex gap-2 mt-4">
      <button 
        @click="handleSave" 
        class="btn-success flex-1"
      >
        保存模板
      </button>
      <button 
        @click="handleReset" 
        class="btn-secondary flex-1"
      >
        重置
      </button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue';
import type { Template, TemplateField } from '../utils/storage';

const props = defineProps<{
  initialTemplate?: Template | null;
  availableTemplates?: Template[];
}>();

const emit = defineEmits<{
  'update-preview': [template: Template];
  'save-template': [template: Template];
  'load-template': [template: Template];
}>();

// 模板数据
const templateData = ref<Template>({
  id: '',
  name: '',
  description: '',
  fields: []
});

// 拖拽相关状态
const draggedIndex = ref<number | null>(null);
const dragOverIndex = ref<number | null>(null);

// 处理类型变更（当类型不是 template 时清空 templateId）
const handleTypeChange = (index: number) => {
  if (templateData.value.fields[index].type !== 'template') {
    templateData.value.fields[index].templateId = '';
  }
};

// 监听初始模板变化
watch(() => props.initialTemplate, (newVal) => {
  if (newVal) {
    templateData.value = { ...newVal };
  }
}, { immediate: true });

// 监听模板数据变化，实时更新预览
watch(templateData, (newVal) => {
  emit('update-preview', newVal);
}, { deep: true });

// 添加字段
const addField = () => {
  templateData.value.fields.push({
    name: '',
    type: 'string',
    required: false,
    constraint: '',
    format: '',
    templateId: ''
  });
};

// 删除字段
const removeField = (index: number) => {
  templateData.value.fields.splice(index, 1);
};

// 保存模板
const handleSave = () => {
  if (!templateData.value.name) {
    alert('请输入模板名称');
    return;
  }
  
  const templateToSave: Template = {
    ...templateData.value,
    id: templateData.value.id || Date.now().toString(),
    createdAt: templateData.value.createdAt || new Date().toISOString()
  };
  
  emit('save-template', templateToSave);
  alert('模板保存成功');
};

// 重置表单
const handleReset = () => {
  templateData.value = {
    id: '',
    name: '',
    description: '',
    fields: []
  };
};

// 拖拽开始
const handleDragStart = (index: number, event: DragEvent) => {
  draggedIndex.value = index;
  if (event.dataTransfer) {
    event.dataTransfer.effectAllowed = 'move';
    event.dataTransfer.setData('text/html', index.toString());
  }
  // 添加拖拽时的样式
  if (event.target instanceof HTMLElement) {
    event.target.style.opacity = '0.5';
  }
};

// 拖拽悬停
const handleDragOver = (event: DragEvent) => {
  event.preventDefault();
  if (event.dataTransfer) {
    event.dataTransfer.dropEffect = 'move';
  }
};

// 拖拽放下
const handleDrop = (targetIndex: number, event: DragEvent) => {
  event.preventDefault();
  
  if (draggedIndex.value === null || draggedIndex.value === targetIndex) {
    return;
  }

  const fields = [...templateData.value.fields];
  const draggedField = fields[draggedIndex.value];
  
  // 移除被拖拽的字段
  fields.splice(draggedIndex.value, 1);
  
  // 在目标位置插入
  fields.splice(targetIndex, 0, draggedField);
  
  // 更新字段数组
  templateData.value.fields = fields;
  
  dragOverIndex.value = null;
};

// 拖拽结束
const handleDragEnd = (event: DragEvent) => {
  draggedIndex.value = null;
  dragOverIndex.value = null;
  // 恢复样式
  if (event.target instanceof HTMLElement) {
    event.target.style.opacity = '1';
  }
};
</script>

<style scoped>
.form-group {
  margin-bottom: 1.5rem;
}

.form-group label {
  display: block;
  margin-bottom: 0.5rem;
  font-weight: 500;
  color: var(--text-primary);
  font-size: 14px;
}

.full-width {
  width: 100%;
}

.button-group {
  display: flex;
  gap: 12px;
}

.btn-primary {
  background: linear-gradient(135deg, var(--primary-color) 0%, #8b5cf6 100%);
  color: white;
  font-weight: 600;
}

.btn-primary:hover {
  background: linear-gradient(135deg, var(--primary-hover) 0%, #7c3aed 100%);
}

.btn-success {
  background: linear-gradient(135deg, var(--success-color) 0%, #059669 100%);
  color: white;
  font-weight: 600;
}

.btn-success:hover {
  background: linear-gradient(135deg, var(--success-hover) 0%, #047857 100%);
}

.btn-secondary {
  background: linear-gradient(135deg, var(--secondary-color) 0%, var(--secondary-hover) 100%);
  color: white;
  font-weight: 600;
}

.btn-secondary:hover {
  background: linear-gradient(135deg, var(--secondary-hover) 0%, #334155 100%);
}

.btn-danger {
  background: linear-gradient(135deg, var(--danger-color) 0%, var(--danger-hover) 100%);
  color: white;
  font-weight: 600;
  padding: 8px 16px;
  font-size: 13px;
}

.btn-danger:hover {
  background: linear-gradient(135deg, var(--danger-hover) 0%, #b91c1c 100%);
}

.flex {
  display: flex;
}

.justify-between {
  justify-content: space-between;
}

.items-center {
  align-items: center;
}

.flex-1 {
  flex: 1;
}

.gap-2 {
  gap: 8px;
}

.w-24 {
  width: 96px;
  min-width: 96px;
}

.w-32 {
  width: 128px;
  min-width: 128px;
}

.w-36 {
  width: 144px;
  min-width: 144px;
}

.w-40 {
  width: 160px;
  min-width: 160px;
}

.field-item {
  background: linear-gradient(135deg, var(--bg-secondary) 0%, var(--bg-tertiary) 100%);
  border: 2px solid var(--border-color);
  padding: 1.25rem;
  margin: 0.75rem 0;
  border-radius: var(--radius-md);
  transition: all 0.2s ease;
  cursor: move;
  position: relative;
}

.field-item:hover {
  border-color: var(--primary-color);
  box-shadow: var(--shadow-sm);
}

.field-item.dragging {
  opacity: 0.5;
  border-color: var(--primary-color);
  box-shadow: var(--shadow-md);
}

.drag-handle {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 24px;
  height: 40px;
  color: var(--text-secondary);
  cursor: grab;
  user-select: none;
  flex-shrink: 0;
  transition: color 0.2s ease;
}

.drag-handle:hover {
  color: var(--primary-color);
}

.drag-handle:active {
  cursor: grabbing;
}

.field-item label {
  font-size: 13px;
  font-weight: 500;
  color: var(--text-secondary);
  margin-bottom: 0.25rem;
}

.field-item input[type="checkbox"] {
  width: auto;
  margin-right: 6px;
  cursor: pointer;
  accent-color: var(--primary-color);
}

.field-item input[type="checkbox"]:checked {
  accent-color: var(--primary-color);
}

.field-item select {
  cursor: pointer;
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 12 12'%3E%3Cpath fill='%236366f1' d='M6 9L1 4h10z'/%3E%3C/svg%3E");
  background-repeat: no-repeat;
  background-position: right 8px center;
  padding-right: 32px;
  appearance: none;
  -webkit-appearance: none;
  -moz-appearance: none;
}

textarea {
  resize: vertical;
  min-height: 60px;
}

/* 字段头部布局 */
.field-header {
  display: flex;
  align-items: center;
  flex-wrap: nowrap;
  gap: 8px;
}

/* 字段输入框样式 */
.field-input {
  flex: 1;
  min-width: 100px;
}

/* 字段选择框样式 */
.field-select {
  width: 100px;
  min-width: 100px;
  flex-shrink: 0;
}

/* 模板选择下拉框样式 */
.field-item select {
  width: 120px;
  min-width: 120px;
  flex-shrink: 0;
}

/* 删除按钮样式优化 */
.btn-small {
  padding: 6px 12px;
  font-size: 13px;
  height: 36px;
  white-space: nowrap;
}

.delete-button {
  flex-shrink: 0;
  min-width: 60px;
}

/* 调整必填复选框的位置 */
.field-item label.flex.items-center {
  display: flex;
  align-items: center;
  margin: 0;
  padding: 0;
  white-space: nowrap;
  flex-shrink: 0;
  min-width: 60px;
}

/* 响应式调整 */
@media (max-width: 1024px) {
  .field-header {
    flex-wrap: wrap;
  }
  
  .field-select, .field-item select {
    width: 100%;
  }
  
  .delete-button {
    width: 100%;
  }
}

@media (max-width: 768px) {
  .field-item {
    padding: 12px;
  }
  
  .field-header > * {
    width: 100%;
  }
}
</style>
